package fw.qaz.asmx.reader.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

import fw.qaz.asmx.reader.R;
import fw.qaz.asmx.reader.adapter.FileListAdapter;
import fw.qaz.asmx.reader.dialog.MyAlertBuilder;
import fw.qaz.asmx.reader.utils.BookShelfUtil;

public class FileBrowseFragment extends Fragment
        implements FileListAdapter.RecyclerViewItemClickListener,
        FileListAdapter.RecyclerViewItemLongClickListener
{
    private TextView tvCurrPath;
    private RecyclerView rvFile;
    private Button btBack;

    private ArrayList<File> fileList = new ArrayList<>();
    private FileListAdapter adapter;

    private File sdRoot = Environment.getExternalStorageDirectory();
    private File currPath;

    public FileBrowseFragment()
    {
    }

    @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        View v=inflater.inflate(R.layout.fragment_file_browse,container,false);
        tvCurrPath = (TextView) v.findViewById(R.id.tv_current_path);
        rvFile = (RecyclerView) v.findViewById(R.id.rv_file_browse);
        btBack = (Button) v.findViewById(R.id.bt_back);
        //
        rvFile.setLayoutManager(new LinearLayoutManager(getActivity()));
        rvFile.addItemDecoration(
                new HorizontalDividerItemDecoration.Builder(getActivity()).build());
        rvFile.setHasFixedSize(true);
        //
        currPath = sdRoot;
        fileList = new ArrayList<>();
        adapter = new FileListAdapter(getActivity(), fileList);
        adapter.setOnClickListener(this);
        adapter.setOnItemLongClickListener(this);
        rvFile.setAdapter(adapter);

        btBack.setOnClickListener(new View.OnClickListener()
        {
            @Override public void onClick(View v)
            {
                backToParentPath();
            }
        });

        listFiles();
        return v;
    }

    @Override public void onItemClick(View v, int pos)
    {
        File f = fileList.get(pos);
        if (f.isDirectory())
        {
            if (f.getName().equals("..."))
            {
                backToParentPath();
                return;
            }
            currPath = f;
            listFiles();
        }
        else
        {
            BookShelfUtil.addBookToJsonFile(f);
            Toast.makeText(getActivity(), R.string.add_success, Toast.LENGTH_SHORT).show();
        }
    }

    @Override public void onItemLongClick(View v, int pos)
    {
        final File f = fileList.get(pos);
        if (f.isDirectory())
        {
            MyAlertBuilder.displayConfimDialog(
                    getActivity(), R.string.tip, R.string.add_books_sure,
                    new DialogInterface.OnClickListener()
                    {
                        @Override public void onClick(DialogInterface dialog, int which)
                        {
                            int cnt = 0;
                            File[] fs = f.listFiles();
                            if (fs != null && fs.length != 0)
                            {
                                for (File f : fs)
                                {
                                    if (f.getName().toLowerCase().endsWith(".txt"))
                                    {
                                        BookShelfUtil.addBookToJsonFile(f);
                                        cnt++;
                                    }
                                }
                                new AlertDialog
                                        .Builder(getActivity())
                                        .setTitle(R.string.tip)
                                        .setMessage("共添加了" + cnt + "本新书！")
                                        .setPositiveButton(android.R.string.yes, null)
                                        .show();
                            }
                            else
                            {
                                Toast.makeText(getActivity(), R.string.no_book_add,
                                               Toast.LENGTH_SHORT)
                                     .show();
                            }
                        }
                    }, null);
        }
        else
        {
            MyAlertBuilder.displayConfimDialog(
                    getActivity(), R.string.tip,
                    R.string.del_sure, new DialogInterface.OnClickListener()
                    {
                        @Override public void onClick(DialogInterface dialog, int which)
                        {
                            if (!f.delete())
                            {
                                MyAlertBuilder
                                        .displayConfimDialog(getActivity(),
                                                             R.string.pay_atation,
                                                             R.string.del_failed, null,
                                                             null);
                                return;
                            }
                            listFiles();
                        }
                    }, null);
        }
    }

    private void listFiles()
    {
        tvCurrPath.setText(currPath.getAbsolutePath());
        fileList.clear();
        File[] files = currPath.listFiles();
        if (files == null || files.length == 0)
        {   //防止空目录
            adapter.notifyDataSetChanged();
            return;
        }
        Arrays.sort(files, new Comparator<File>()
        {
            @Override public int compare(File l, File r)
            {
                //目录在前
                //字母序在前
                if (l.isDirectory() && r.isDirectory())
                {
                    return l.getName().toLowerCase().compareTo(r.getName().toLowerCase());
                }
                if (l.isDirectory())
                {
                    return -1;
                }
                else if (r.isDirectory())
                {
                    return 1;
                }
                return l.getName().toLowerCase().compareTo(r.getName().toLowerCase());
            }
        });

        for (File f : files)
        {
            if (currPath.equals(sdRoot) && f.getName().equals("..."))
            {
                continue;
            }
            if (f.isDirectory() || f.getName().toLowerCase().endsWith(".txt"))
            {
                fileList.add(f);
            }
        }
        adapter.notifyDataSetChanged();

        if (currPath.equals(sdRoot))
        {
            btBack.setEnabled(false);
        }
        else
        {
            btBack.setEnabled(true);
        }
    }

    public boolean backToParentPath()
    {
        if (currPath.equals(sdRoot))
        {
            return true;
        }
        currPath = currPath.getParentFile();
        listFiles();
        return false;
    }
}
